package com.pig4cloud.pig.model.listener;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.gson.JsonObject;
import com.pig4cloud.pig.admin.api.entity.SysUser;
import com.pig4cloud.pig.model.api.dto.ManagementDto;
import com.pig4cloud.pig.model.api.dto.OptLogDTO;
import com.pig4cloud.pig.model.api.entity.ModelLogEntity;
import com.pig4cloud.pig.model.api.entity.ManagementEntity;
import com.pig4cloud.pig.model.event.ModelLogEvent;
import com.pig4cloud.pig.model.service.ManagementService;
import com.pig4cloud.pig.model.service.ModelLogService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.net.MalformedURLException;
import java.net.URL;

/**
 * packageName com.pig4cloud.pig.model.listener
 *
 * @author marco
 * @className ModelLogListener (此处以class为例)
 * @date 2024/6/14
 * @description 异步监听日志事件
 */
@Component
@RequiredArgsConstructor
public class ModelLogListener {
	private final ModelLogService modelLogService;
	private final ManagementService managementService;

	    @Async//异步处理
		@EventListener(ModelLogEvent.class)
		public void saveSysLog(ModelLogEvent event) throws MalformedURLException {
			OptLogDTO logDTO = (OptLogDTO) event.getSource();
		    ManagementDto params = logDTO.getParams();
			ManagementEntity managementEntity=managementService.getById(logDTO.getModelId());
			ModelLogEntity modelLogEntity=new ModelLogEntity();
			if(managementEntity!=null){
				modelLogEntity.setTitle(managementEntity.getName());
				modelLogEntity.setVersion(managementEntity.getVersion());
				modelLogEntity.setHeader(managementEntity.getHeader());
			}
			long id = Thread.currentThread().getId();
			//TODO 可以输出日志到数据库
			System.out.println("监听到日志操作事件：" +logDTO + " 线程id：" + id);
			//将日志信息保存到数据库
		    BeanUtil.copyProperties(logDTO,modelLogEntity);
			modelLogEntity.setThreadId(id);
			modelLogEntity.setUrl(params.getUrl());
			modelLogEntity.setParameter(params.getParameter());
			modelLogEntity.setParameterType(params.getParameterType());
			modelLogService.save(modelLogEntity);
		}
	}
